package com.sharding.sphere.demo.algorithm;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.config.sharding.strategy.ComplexShardingStrategyConfiguration;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.core.strategy.route.complex.ComplexShardingStrategy;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author: shuguang.zhang
 * @date : 2021-06-04 17:02
 */
@Slf4j
public class TradeOrderTableComplexShardingStrategy implements ComplexKeysShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> tablesName, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        log.info("TradeOrderTableComplexShardingStrategy ---> tablesName:[{}] complexKeysShardingValue:[{}]", tablesName, complexKeysShardingValue);

        String logicTableName = complexKeysShardingValue.getLogicTableName();

        List<String> list = new ArrayList<>();
        Map<String /** 分片的键 */ , Collection<Long> /** 具体的数据 */> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();

        List<Long> tradeOrderNo = (List<Long>) columnNameAndShardingValuesMap.get("trade_order_no");
        List<Long> id = (List<Long>) columnNameAndShardingValuesMap.get("id");
        for (int i = 0; i < tradeOrderNo.size(); i++) {
            Long aLong = id.get(i);
            BigInteger add = BigInteger.valueOf(aLong + tradeOrderNo.get(i)).mod(BigInteger.valueOf(2L)).add(new BigInteger("1"));
            list.add(logicTableName.concat("_").concat(add.toString()));
        }

        Map<String, Range<Long>> columnNameAndRangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap();

        return list;
    }
}
